package com.seari.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.DatatypeConverter;

import org.apache.commons.lang3.StringUtils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtil
{
	/**
	 * JWT签发人
	 */
	private static final String ISSUER = "seariMetro";

	/**
	 * 有效时间24小时
	 */
	private static final long EXPIRATION = 24 * 60 * 60 * 1000;

	private static final String SECRET_KEY = "seariMetroSupport";

	/**
	 * 生成JWT TOKEN
	 * 
	 * @param tokenId
	 *            令牌ID
	 * @param subject
	 *            账号
	 * @return
	 */
	public static final String createJWT(String tokenId, String userName ,String stationName)
	{
		// 当前时间
		long currentTimeMillis = System.currentTimeMillis();
		byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(SECRET_KEY);// 秘钥
		JwtBuilder jwt = Jwts.builder();
		if (!StringUtils.isEmpty(tokenId))
		{
			jwt.setId(tokenId);
		}
		jwt.setSubject(userName);
		if(StringUtils.isNotBlank(stationName))
		{
			Map<String, Object> claim = new HashMap<>();
			claim.put("stationName",stationName);
			jwt.addClaims(claim);
		}
		jwt.setIssuer(ISSUER);
		jwt.setIssuedAt(new Date(currentTimeMillis));
		jwt.setExpiration(new Date(currentTimeMillis + EXPIRATION));
		// 压缩，可选GZIP
		jwt.compressWith(CompressionCodecs.GZIP);
		// 加密设置
		jwt.signWith(SignatureAlgorithm.HS256, secretKeyBytes);
		return jwt.compact();
	}

	/**
	 * 解密jwt
	 * 
	 * @param jwt
	 * @return
	 */
	public static final Claims parseJWT(String jwt)
	{
		Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(SECRET_KEY)).parseClaimsJws(jwt)
				.getBody();
		return claims;
	}
}
